package com.yaoyanshe.trialfield.network

import android.util.Log
import com.google.gson.Gson
import com.yaoyanshe.trialfield.network.interceptor.SytLoggingInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *<p>description:</p>
 *<p>created on: 2020/9/20 14:41</p>
 * @author tck
 * @version v1.3.0
 *
 */

class ApiFactory private constructor() {

    private lateinit var retrofit: Retrofit
    private lateinit var client: OkHttpClient
    private lateinit var gson: Gson
    private var BASE_URL: String = ""

    companion object {
        const val SERVER_PATH: String = "pmcp-app/"

        val instance: ApiFactory by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ApiFactory()
        }
    }

    fun init(serverUrl: String, interceptor: Interceptor? = null) {
        gson = Gson().newBuilder()
                .setLenient()
                .serializeNulls()
                .create()

        val okHttpClientBuild = OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .callTimeout(60, TimeUnit.SECONDS)

        interceptor?.let {
            okHttpClientBuild.addInterceptor(it)
        }

        if (BuildConfig.DEBUG) {
            okHttpClientBuild.addInterceptor(SytLoggingInterceptor())
        }

        client = okHttpClientBuild.build()

        BASE_URL = serverUrl + SERVER_PATH

        retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()
    }


    fun <T> getService(service: Class<T>): T {
        return retrofit.create(service)
    }

}